package com.hefan.common.oss;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.cat.common.util.GuuidUtil;
import com.cat.tiger.util.DateUtils;
import com.cat.tiger.util.GlobalConstants;
import com.hefan.common.ons.ONSConstants;
import com.hefan.common.oss.dao.OssUploadCfgVo;
import org.springframework.stereotype.Component;

import java.sql.Date;

/**
 * Created by kevin_zhang on 01/03/2017.
 */
@Component("aliOssService")
public class AliOssServiceImpl implements AliOssService {
    public static String endpoint = "oss-cn-beijing.aliyuncs.com";

    /**
     * 获取上传图片所需的签名等认证信息
     *
     * @param expireTime
     * @return
     */
    @Override
    public OssUploadCfgVo getOssUploadCfgInfo(long expireTime) {
        OssUploadCfgVo result = new OssUploadCfgVo();
        result.setAccessid(ONSConstants.AccessKey);

        String _bucket = GlobalConstants.PIC_OSS_BUCKET; //存储空间（Bucket）
        String _endpoint = endpoint; //Endpoint（访问域名）
        String _dir = DateUtils.currentDate(DateUtils.YYYYMMDD) + "/" + GuuidUtil.getUuid(); //存储路径
        String _host = "http://" + _bucket + "." + _endpoint; // host
        OSSClient client = new OSSClient(_endpoint, ONSConstants.AccessKey, ONSConstants.SecretKey);
        try {
            long expireEndTime = System.currentTimeMillis() + expireTime;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, _dir);

            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = client.calculatePostSignature(postPolicy);

            result.setDir(_dir);
            result.setHost(_host);
            result.setPolicy(encodedPolicy);
            result.setSignature(postSignature);
            result.setExpireTime(expireTime);
            result.setExpireEndTime(expireEndTime);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}